### Table A20 ###

rm (list=ls ()) 
# Load packages 
library(readstata13)
library(ggplot2)
library(dplyr)
library(reshape2)
library(lfe)
library(stargazer)


# Read Replication data 
base <- read.dta13("~/Dropbox/Replication_MVC/Datasets/datasets_analysis/panel_excombatientes.dta",
                   convert.factors = TRUE, generate.factors = FALSE,
                   encoding = "UTF-8", fromEncoding = NULL, convert.underscore = FALSE,
                   missing.type = FALSE, convert.dates = TRUE, replace.strl = TRUE,
                   add.rownames = FALSE, nonint.factors = TRUE, select.rows = NULL)

base <- base %>%                            
    group_by(codigoespejo) %>%
    dplyr::mutate(laggedval = lag(year, n = 1, default = NA, order_by = year),
                  PONAL_CAPTURES = ifelse(is.na(laggedval), 
                                          NdeCapturasCrucePONAL,diffcaptures),
                  FLAGRANT_CAPTURES = ifelse(is.na(laggedval), 
                                             NdeCapturasenFlagrancia,diffcaptures_f)) %>% 
    dplyr::ungroup()

base_mun <- base %>% 
    dplyr::group_by (origmun, year) %>% 
    dplyr::summarise (
        oro_sin_titulo = mean (oro_sin_titulo, na.rm = TRUE)
        , sum_PONAL = sum (PONAL_CAPTURES, na.rm = TRUE)
        , sum_FLAGRANT = sum(FLAGRANT_CAPTURES, na.rm = TRUE)
        , GOLD_PRICE_MEAN = mean(gold_price, na.rm = TRUE))


summary (modpoolPONALminas <- felm (sum_PONAL ~ oro_sin_titulo | 0 | 0 | 0, data=base_mun))
summary (modpoolPONALoro <- felm (sum_PONAL ~ GOLD_PRICE_MEAN | 0 | 0 | 0, data=base_mun))
summary (modpoolFLAGminas <- felm (sum_FLAGRANT ~ oro_sin_titulo | 0 | 0 | 0, data=base_mun))
summary (modpoolFLAGoro <- felm (sum_FLAGRANT ~ GOLD_PRICE_MEAN | 0 | 0 | 0, data=base_mun))


stargazer(modpoolPONALminas, modpoolPONALoro, modpoolFLAGminas, modpoolFLAGoro,
    type = "latex",                 # Output type changed to LaTeX
    dep.var.labels = c("PONAL CAPTURES", "FLAGRANT CAPTURES"),
    title = "Pooled models",
    out = "models.tex"              # Output file extension changed to .tex
)


